package com.mycompany.baoming.service;

import com.mycompany.baoming.dao.BaomingDao;
import com.mycompany.baoming.entity.*;
import com.mycompany.mvc.utils.EasyResult;
import com.mycompany.mvc.utils.SystemConstant;
import com.mycompany.mvc.utils.SystemUtil;
import com.mycompany.user.entity.User;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by Jintao_Ma on 2017/9/16.
 */
@Service("baomingService")
public class BaomingServiceImpl implements BaomingService{

    Logger logger = LoggerFactory.getLogger(BaomingServiceImpl.class);

    @Autowired
    private BaomingDao baomingDao;

    //查询出来的字段渲染
    public void render(List<Baoming> bmList){
        if(CollectionUtils.isNotEmpty(bmList)){
            for (Baoming baoming:bmList){
                //性别
                if(StringUtils.equals(baoming.getSex(),"A") ){
                    baoming.setSex("男");
                }else if(StringUtils.equals(baoming.getSex(),"B")){
                    baoming.setSex("女");
                }
                //参赛项目
                String bsInfo = baoming.getBsInfo();
                if(StringUtils.isNotEmpty(bsInfo)){
                    bsInfo = bsInfo.replaceAll("A","自由体操 ").replace("B","高低杠 ")
                            .replaceAll("C","双杠 ").replace("D","吊环 ")
                            .replaceAll("E","全能 ").replace("F","跳马 ")
                            .replaceAll("G","鞍马 ").replace("H","平衡木 ")
                            .replaceAll("I","单杠 ");
                    baoming.setBsInfo(bsInfo);
                }

                //参赛组别
                String team = baoming.getTeam();
                if(StringUtils.isNotEmpty(team)){
                    team = team.replaceAll("A","男子五岁 ").replace("B","男子六岁 ")
                            .replaceAll("C","男子七岁 ").replace("D","男子八岁 ")
                            .replaceAll("E","女子五岁 ").replace("F","女子六岁 ")
                            .replaceAll("G","女子七岁").replace("H","女子八岁 ");
                    baoming.setTeam(team);
                }
            }
        }
    };

    @Override
    public EasyResult getUserBmList(Map<String, Object> map) {
        EasyResult easyResult = new EasyResult();
        List<Baoming> list = new ArrayList<>();
        List<Baoming> countList = new ArrayList<>();
        Map<String,Object> countMap = new HashMap<>(map);
        countMap.put("page",null);
        countMap.put("rows",null);

        /*可以由controller层携带参数*/
        try {
            list = baomingDao.getBmList(map);
            countList = baomingDao.getBmList(countMap);
            easyResult.setSuccess(true);
            easyResult.setMsg(SystemConstant.returnSucMsg);
            easyResult.setTotal(null != countList?countList.size():0);
            //渲染字段,比如性别,参赛信息
            render(list);
            easyResult.setRows(list);
        } catch (Exception e) {
            easyResult.setSuccess(false);
            easyResult.setMsg(SystemConstant.returnFalMsg+":"+e.getMessage());
            e.printStackTrace();
        }
        return  easyResult;
    }

    public EasyResult getUserBmListOr(Map<String, Object> map) {
        EasyResult easyResult = new EasyResult();
        List<Baoming> list = new ArrayList<>();
        List<Baoming> countList = new ArrayList<>();
        Map<String,Object> countMap = new HashMap<>(map);
        countMap.put("page",null);
        countMap.put("rows",null);

        /*可以由controller层携带参数*/
        try {
            countList = baomingDao.getBmList(countMap);
            if(null != countList && countList.size() >0){
                easyResult.setSuccess(false);
            }else{
                easyResult.setSuccess(true);
            }
        } catch (Exception e) {
            easyResult.setSuccess(false);
            easyResult.setMsg(SystemConstant.returnFalMsg+":"+e.getMessage());
            e.printStackTrace();
        }
        return  easyResult;
    }

    @Override
    public EasyResult UserBmSave(HttpServletRequest request){
        EasyResult easyResult = new EasyResult();
        Baoming baoming = new Baoming();

        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile shenfenInfoFile = multipartRequest.getFile("shenfenInfo");
            MultipartFile jiankangInfoFile = multipartRequest.getFile("jiankangInfo");
            MultipartFile baoxianInfoFile = multipartRequest.getFile("baoxianInfo");
            MultipartFile jiaofeiInfoFile = multipartRequest.getFile("jiaofeiInfo");
            List<MultipartFile> fileList = new ArrayList<>();
            fileList.addAll(Arrays.asList(shenfenInfoFile,jiankangInfoFile,baoxianInfoFile,jiaofeiInfoFile));
            if(CollectionUtils.isNotEmpty(fileList)){
                String savaPath = ""; //文件的保存路径
                for (MultipartFile multipartFile : fileList) {
                     try {
                        if(SystemUtil.isNotNull(multipartFile) && !multipartFile.isEmpty()){
                            if(StringUtils.equals(multipartFile.getName(),"shenfenInfo")){
                                savaPath = SystemUtil.saveFile(multipartFile,request);
                                if(StringUtils.isNotEmpty(savaPath)){
                                    logger.info("单文件保存成功，文件路径为:"+savaPath);
                                    baoming.setShenfenInfo(savaPath);
                                }
                            }else if(StringUtils.equals(multipartFile.getName(),"jiankangInfo")){
                                savaPath = SystemUtil.saveFile(multipartFile,request);
                                if(StringUtils.isNotEmpty(savaPath)){
                                    logger.info("单文件保存成功，文件路径为:"+savaPath);
                                    baoming.setJiankangInfo(savaPath);
                                }
                            }else if(StringUtils.equals(multipartFile.getName(),"baoxianInfo")){
                                savaPath = SystemUtil.saveFile(multipartFile,request);
                                if(StringUtils.isNotEmpty(savaPath)){
                                    logger.info("单文件保存成功，文件路径为:"+savaPath);
                                    baoming.setBaoxianInfo(savaPath);
                                }
                            }else if(StringUtils.equals(multipartFile.getName(),"jiaofeiInfo")){
                                savaPath = SystemUtil.saveFile(multipartFile,request);
                                if(StringUtils.isNotEmpty(savaPath)){
                                    logger.info("单文件保存成功，文件路径为:"+savaPath);
                                    baoming.setJiaofeiInfo(savaPath);
                                }
                            }
                        }
                     } catch (Exception e) {
                        logger.error("单文件上传失败:"+e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
            //获取普通的元素
            Integer userId = Integer.valueOf(multipartRequest.getParameter("userId"));
            String name = multipartRequest.getParameter("name");
            String idCard = multipartRequest.getParameter("idCard");
            String sex = multipartRequest.getParameter("sex");
            String phone = multipartRequest.getParameter("phone");
            String address = multipartRequest.getParameter("address");
            String city = multipartRequest.getParameter("city");
            String team = multipartRequest.getParameter("team");
            String age = multipartRequest.getParameter("age");
            String coach = multipartRequest.getParameter("coach");
            String clo = multipartRequest.getParameter("clo");
            String teaTime = multipartRequest.getParameter("teaTime");
            String love = multipartRequest.getParameter("love");
            String dream = multipartRequest.getParameter("dream");
            String bsInfo = multipartRequest.getParameter("bsInfo");
            String channel = multipartRequest.getParameter("channel");
            if(StringUtils.isNotEmpty(bsInfo)){
                //报名的项目以逗号分隔
                baoming.setBsInfo(bsInfo);
                logger.info("报名信息:"+bsInfo);
            }
            baoming.setUserId(userId);
            baoming.setName(name);
            baoming.setIdCard(idCard);
            baoming.setSex(sex);
            baoming.setPhone(phone);
            baoming.setAddress(address);
            baoming.setCity(city);
            baoming.setTeam(team);
            baoming.setClo(clo);

            baoming.setAge(age);
            baoming.setCoach(coach);
            //不同组织设置不同的账号
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            if(null != user){
                Integer roleId = user.getRoleId();
                if(null != roleId){
                    if(roleId == 3){
                        baoming.setOrgName("个人");
                    }else if(roleId == 2){
                        baoming.setOrgName(user.getUserName());
                    }
                }
            }
            baoming.setTeaTime(teaTime);
            baoming.setLove(love);
            baoming.setDream(dream);

            baoming.setCreateTime(new Date());
            baomingDao.addBm(baoming);
            easyResult.setSuccess(true);
            easyResult.setMsg(SystemConstant.returnSucMsg);
        } catch (Exception e) {
            ;logger.error("多文件上传失败:"+e.getMessage());
            e.printStackTrace();
            easyResult.setSuccess(false);
            easyResult.setMsg(SystemConstant.returnFalMsg);
        }
        return easyResult;
    }

    @Override
    public ModelAndView UserBmToEdit(Map<String, Object> map) {
        ModelAndView mv = new ModelAndView("/system/user/userEdit");

        /*根据ID查询唯一记录*/
        List<Baoming> baomingList = baomingDao.getAllByParam(map);
        Baoming baoming = CollectionUtils.isNotEmpty(baomingList)? baomingList.get(0):new Baoming();
        List<SexDic> sexDic = BmDicConstant.getSexDic();
        List<CansaiDic> ItemDic = BmDicConstant.getCansaiDic();
        List<ProDic> ProList = BmDicConstant.getProDic();
        List<ProDic> ProListW5 = BmDicConstant.getPro5Dic();
        List<ProDic> ProListW6 = BmDicConstant.getPro6Dic();
        List<ProDic> ProListWA = BmDicConstant.getProWDic();
        List<ProDic> TeamList = BmDicConstant.getTeamDic();
        List<ProDic> CloDic = BmDicConstant.getCloDic();

        mv.addObject("ProList",ProList);
        mv.addObject("ProListW5",ProListW5);
        mv.addObject("ProListW6",ProListW6);
        mv.addObject("ProListWA",ProListWA);
        mv.addObject("TeamList",TeamList);
        mv.addObject("CloDic",CloDic);
        mv.addObject("sexDic",sexDic);

        mv.addObject("ItemDic",ItemDic);
        mv.addObject("baoming",baoming);

        return mv;
    }

    @Override
    public ModelAndView OrgBmToEdit(Map<String, Object> map) {
        ModelAndView mv = new ModelAndView("/system/org/orgEdit");

        /*根据ID查询唯一记录*/
        List<Baoming> baomingList = baomingDao.getAllByParam(map);
        Baoming baoming = CollectionUtils.isNotEmpty(baomingList)? baomingList.get(0):new Baoming();
        List<SexDic> sexDic = BmDicConstant.getSexDic();
        List<CansaiDic> ItemDic = BmDicConstant.getCansaiDic();
        List<ProDic> ProList = BmDicConstant.getProDic();
        List<ProDic> ProListW5 = BmDicConstant.getPro5Dic();
        List<ProDic> ProListW6 = BmDicConstant.getPro6Dic();
        List<ProDic> ProListWA = BmDicConstant.getProWDic();
        List<ProDic> TeamList = BmDicConstant.getTeamDic();
        List<ProDic> CloDic = BmDicConstant.getCloDic();

        mv.addObject("ProList",ProList);
        mv.addObject("ProListW5",ProListW5);
        mv.addObject("ProListW6",ProListW6);
        mv.addObject("ProListWA",ProListWA);
        mv.addObject("TeamList",TeamList);
        mv.addObject("CloDic",CloDic);
        mv.addObject("sexDic",sexDic);

        mv.addObject("ItemDic",ItemDic);
        mv.addObject("baoming",baoming);

        return mv;
    }

    @Override
    public EasyResult UserBmDelete(Map<String, Object> map) {
        EasyResult easyResult = new EasyResult();

        try {
            baomingDao.deleteByParam(map);
            easyResult.setSuccess(true);
            easyResult.setMsg(SystemConstant.returnSuc);
            logger.info("删除成功:"+MapUtils.getInteger(map,"id"));
        } catch (Exception e) {
            easyResult.setSuccess(false);
            easyResult.setMsg(SystemConstant.returnFal);
            logger.info("删除失败:"+e.getMessage());
            e.printStackTrace();
        }

        return easyResult;
    }

    @Override
    public EasyResult UserBmEdit(HttpServletRequest request){
        EasyResult easyResult = new EasyResult();
        Baoming baoming = new Baoming();

        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile shenfenInfoFile = multipartRequest.getFile("shenfenInfo");
            MultipartFile jiankangInfoFile = multipartRequest.getFile("jiankangInfo");
            MultipartFile baoxianInfoFile = multipartRequest.getFile("baoxianInfo");
            MultipartFile jiaofeiInfoFile = multipartRequest.getFile("jiaofeiInfo");
            List<MultipartFile> fileList = new ArrayList<>();
            fileList.addAll(Arrays.asList(shenfenInfoFile,jiankangInfoFile,baoxianInfoFile,jiaofeiInfoFile));
            if(CollectionUtils.isNotEmpty(fileList)){
                String savaPath = ""; //文件的保存路径
                for (MultipartFile multipartFile : fileList) {
                    try {
                        if(SystemUtil.isNotNull(multipartFile) && !multipartFile.isEmpty()){
                            if(StringUtils.equals(multipartFile.getName(),"shenfenInfo")){
                                savaPath = SystemUtil.saveFile(multipartFile,request);
                                if(StringUtils.isNotEmpty(savaPath)){
                                    logger.info("单文件保存成功，文件路径为:"+savaPath);
                                    baoming.setShenfenInfo(savaPath);
                                }
                            }else if(StringUtils.equals(multipartFile.getName(),"jiankangInfo")){
                                savaPath = SystemUtil.saveFile(multipartFile,request);
                                if(StringUtils.isNotEmpty(savaPath)){
                                    logger.info("单文件保存成功，文件路径为:"+savaPath);
                                    baoming.setJiankangInfo(savaPath);
                                }
                            }else if(StringUtils.equals(multipartFile.getName(),"baoxianInfo")){
                                savaPath = SystemUtil.saveFile(multipartFile,request);
                                if(StringUtils.isNotEmpty(savaPath)){
                                    logger.info("单文件保存成功，文件路径为:"+savaPath);
                                    baoming.setBaoxianInfo(savaPath);
                                }
                            }else if(StringUtils.equals(multipartFile.getName(),"jiaofeiInfo")){
                                savaPath = SystemUtil.saveFile(multipartFile,request);
                                if(StringUtils.isNotEmpty(savaPath)){
                                    logger.info("单文件保存成功，文件路径为:"+savaPath);
                                    baoming.setJiaofeiInfo(savaPath);
                                }
                            }
                        }
                    } catch (Exception e) {
                        logger.error("单文件上传失败:"+e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
            //获取普通的元素
            Integer id = Integer.valueOf(multipartRequest.getParameter("id"));
            Integer userId = Integer.valueOf(multipartRequest.getParameter("userId"));
            String name = multipartRequest.getParameter("name");
            String idCard = multipartRequest.getParameter("idCard");
            String sex = multipartRequest.getParameter("sex");
            String phone = multipartRequest.getParameter("phone");
            String address = multipartRequest.getParameter("address");
            String city = multipartRequest.getParameter("city");
            String bsInfo = multipartRequest.getParameter("bsInfo");
            String team = multipartRequest.getParameter("team");
            String age = multipartRequest.getParameter("age");
            String coach = multipartRequest.getParameter("coach");
            String clo = multipartRequest.getParameter("clo");
            String teaTime = multipartRequest.getParameter("teaTime");
            String love = multipartRequest.getParameter("love");
            String dream = multipartRequest.getParameter("dream");

            if(StringUtils.isNotEmpty(bsInfo)){
                //报名的项目以逗号分隔
                baoming.setBsInfo(bsInfo);
                logger.info("报名信息:"+bsInfo);
            }
            baoming.setId(id);
            baoming.setUserId(userId);
            baoming.setName(name);
            baoming.setIdCard(idCard);
            baoming.setSex(sex);
            baoming.setPhone(phone);
            baoming.setAddress(address);
            baoming.setCity(city);

            baoming.setTeam(team);
            baoming.setClo(clo);
            baoming.setAge(age);
            baoming.setCoach(coach);
            baoming.setTeaTime(teaTime);
            baoming.setLove(love);
            baoming.setDream(dream);

//            baoming.setCreateTime(new Date());
            baoming.setUpdateTime(new Date());
            baomingDao.updateBm(baoming);
            easyResult.setSuccess(true);
            easyResult.setMsg(SystemConstant.returnSucMsg);
        } catch (Exception e) {
            ;logger.error("多文件上传失败:"+e.getMessage());
            e.printStackTrace();
            easyResult.setSuccess(false);
            easyResult.setMsg(SystemConstant.returnFalMsg);
        }
        return easyResult;
    }
}
